import axios from 'axios';
import { showErrorMessage, showHttpErrorMessage } from './msg';
import { ResultEnum, ContentTypeEnum } from '/@/enums/httpEnum';

export function fileDownload(method: string, url: string, token: string, params: any, callFun: any, resolve: any, reject: any) {
	axios({
		method: method,
		url: url,
		headers: {
			'Content-Type': ContentTypeEnum.JSON,
			Authorization: token,
		},
		responseType: 'blob',
		params: params,
		timeout: 120 * 1000,
		onDownloadProgress: function (progressEvent) {
			if (callFun?.callback && typeof callFun.callback === "function")  {
				callFun.callback('onDownloadProgress', progressEvent);
			}
		},
	})
		.then((res) => {
			// console.log('文件流下载', res);
			const { data, headers } = res;

			// 检验后台报错
			if (data.type === 'application/json') {
				let reader = new FileReader();
				// blob数据转换json
				reader.onload = (e: any) => {
					const jsonData = JSON.parse(e.target.result);
					showErrorMessage(jsonData);
					reject(jsonData);
				};
				reader.readAsText(data);
				return;
			}

			let fileName: string;
			if (headers['content-disposition']) {
				const filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
				const matches = filenameRegex.exec(decodeURIComponent(headers['content-disposition']));
				fileName = matches != null && matches[1] ? matches[1].replace(/['"]/g, '') : '未知文件';
			} else if (res.config.params?.file_name) {
				fileName = res.config.params.file_name;
			} else {
				fileName = data.fileName;
			}

			const blob = new Blob([data], { type: headers['content-type'] });
			const downloadElement = document.createElement('a');
			const href = window.URL.createObjectURL(blob);
			downloadElement.href = href;
			downloadElement.download = fileName;
			document.body.appendChild(downloadElement);
			downloadElement.click();
			document.body.removeChild(downloadElement);
			window.URL.revokeObjectURL(href);
			resolve(res.data);
		})
		.catch((err) => {
			showHttpErrorMessage(err);
			reject(err.response);
		});
}

export function fileImport(url: string, token: string, params: any, callFun: any, resolve: any, reject: any) {
	axios
		.post(url, params, {
			headers: {
				'Content-Type': ContentTypeEnum.FORM_DATA,
				Authorization: token,
			},
			timeout: 120 * 1000,
			onUploadProgress: function (progressEvent) {
				if (callFun?.callback && typeof callFun.callback === "function")  {
					callFun.callback('onUploadProgress', progressEvent);
				}
			},
		})
		.then((res) => {
			// console.log('文件导入', res);
			const { data, headers } = res;

			window.console.log(data);
			if (data.code === ResultEnum.SUCCESS) {
				resolve(data);
			} else {
				showErrorMessage(data);
				reject(data);
			}
		})
		.catch((err) => {
			showHttpErrorMessage(err);
			reject(err.response);
		});
}
